package com.zjgk.hotel.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import com.zjgk.hotel.dao.pojo.User;
import com.zjgk.hotel.service.impl.UserServiceImpl;
import com.zjgk.hotel.utils.UserThreadLocal;
import com.zjgk.hotel.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserServiceImpl userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        前置中间件

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        String token = request.getHeader("Authorization");
        if (StringUtils.isBlank(token)) {
            String result = JSONObject.toJSONString(new Result(Result.NOT_LOGGED, "未登入"));
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(result);
            return false;
        }
        String s = userService.checkToken(token);

        if (StringUtils.isBlank(s)) {
            String result = JSONObject.toJSONString(new Result(Result.NOT_LOGGED, "未登入"));
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(result);
            return false;

        }

        request.setAttribute("userInfo",s);
        User user = JSON.parseObject(s, User.class);
        UserThreadLocal.put(user);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //后置中间件
    }
}
